package ch.bfh.mobicomp;

import java.util.LinkedList;
import java.util.List;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

public class AccelerometerEventListener implements SensorEventListener {
	private List<SensorListener> listener = new LinkedList<SensorListener>();
	private SensorManager manager = null;
	private static final int BUFFER_SIZE = 5;
	private float[] buffer = new float[BUFFER_SIZE];
	private int bufferIndex = 0;

	public void addAccelerometerActionListener(SensorListener listener) {
		this.listener.add(listener);

		refreshEventBinding();
	}

	public void removeAccelerometerActionListener(SensorListener listener) {
		this.listener.remove(listener);

		refreshEventBinding();
	}

	private void refreshEventBinding() {
		if (listener.size() > 0)
			manager.registerListener((SensorEventListener) this,
					manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
					SensorManager.SENSOR_DELAY_NORMAL);
		else {
			manager.unregisterListener(this);
		}
	}

	public AccelerometerEventListener(SensorManager manager) {
		this.manager = manager;
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		buffer[bufferIndex] = Math.abs(event.values[0])
				+ Math.abs(event.values[1]) + Math.abs(event.values[2]);
		bufferIndex++;
		bufferIndex %= BUFFER_SIZE;

		float minValue = Integer.MAX_VALUE;
		float maxValue = Integer.MIN_VALUE;

		if (bufferIndex == BUFFER_SIZE - 1) {
			for (int i = 0; i < buffer.length; i++) {
				if (minValue > buffer[i])
					minValue = buffer[i];

				if (maxValue < buffer[i])
					maxValue = buffer[i];
			}
			Log.d("SENSOR", String.valueOf(maxValue - minValue));
			
			if(maxValue - minValue > 5)
				if (listener != null)
					for (SensorListener l : listener)
						l.onSensorChanged();
		}
	}

}
